package com.ruoyi.project.tool.upload.service.impl;

import com.ruoyi.common.utils.AliyunOssUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.tool.upload.service.UploadService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.Locale;

/***
 * 上传图片
 */
@Service
public class UploadServiceImpl implements UploadService{

    @Autowired
    private AliyunOssUtil aliyunOssUtil;

    /**
     * 单张上传
     * @param picFile
     * @param type
     * @return
     */
    public String uploadImage(MultipartFile picFile,String type) {
        if (!StringUtils.isBlank(type)) {
            //获取后缀
            String ext = FilenameUtils.getExtension(picFile.getOriginalFilename()).toLowerCase(Locale.ENGLISH);
            String path = type+"/"+StringUtils.getOrderIdByUUId() + "." + ext;
            aliyunOssUtil.uploadImageToOSS(picFile,path);
            return path;
        }
        return null;
    }

    /**
     * 批量上传
     * @param picFile
     * @param type
     * @return
     */
    public String uploadImages(MultipartFile[] picFile,String type) {
        if (!StringUtils.isBlank(type)) {
            try {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < picFile.length; i++) {
                    String ext = FilenameUtils.getExtension(picFile[i].getOriginalFilename()).toLowerCase(Locale.ENGLISH);
                    String path = type+"/"+StringUtils.getOrderIdByUUId()+ "." + ext;
                    aliyunOssUtil.uploadImageToOSS(picFile[i],path);
                    sb.append(path).append(",");//原图存阿里云
                }
                return sb.deleteCharAt(sb.length()-1).toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /***
     * 删除图片
     * @param filePath 以逗号隔开
     * @return
     */
    public AjaxResult delImage(@RequestParam("filePath") String filePath){
        String[] path = filePath.split(",");
        for(int i=0;i<path.length;i++){
            aliyunOssUtil.deleteImage(path[i]);
        }
        return AjaxResult.success("删除成功");
    }
}
